package com.yy.tech.data.provider.loader;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yy.tech.data.provider.model.SecretRules;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractResourceLoader<T> implements ResourceLoader<T> {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	protected ObjectMapper mapper = new ObjectMapper();

	@Override
	public List<T> load(final String path, final String post, final TypeReference<T> typeReference) {
		final List<T> list = new ArrayList<>();
		final String uri = getPath(path, post);
		try {
			final Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader())
					.getResources("classpath:" + uri);
			if (null != resources) {
				for (final Resource r : resources) {
					T t= mapper.readValue(r.getInputStream(), typeReference);
					list.add(t);
				}
			}
		} catch (final Exception e) {
			logger.warn("Load resource[{}] exception :{}", uri, e.getMessage());
		}
		return list;
	}

	protected String getPath(final String path, final String post) {
		final StringBuilder sb = new StringBuilder();
		if (!StringUtils.isEmpty(path)) {
			sb.append(path);
		}
		if (!StringUtils.isEmpty(post)) {
			if (sb.length() > 0 && !path.endsWith("/") && !post.startsWith("/")) {
				sb.append("/");
			}
			sb.append(post);
		}
		return sb.toString();
	}

}
